# coding=utf-8
import urlparse
from bs4 import BeautifulSoup

from html_crawler import HtmlCrawler


class HtmlParser(object):

    def parse(self, html_content, page_url, page_type):
        soup = BeautifulSoup(html_content, 'html.parser')
        if page_type == 'wordbook':
            return self.__get_wordbook_links(soup, page_url)
        elif page_type == 'wordlist':
            return self.__get_wordlist_word(soup)

    @classmethod
    def __get_wordbook_links(cls, soup, page_url):
        links = []
        wordbook_links = soup.find('div', id='wordbook-wordlist-container')\
            .find_all('div', class_='wordbook-create-candidate-wordlist wordbook-containing-wordlist')

        for link in wordbook_links:
            link_data = link.find('a')
            links.append(urlparse.urljoin(page_url, link_data['href']))

        return links

    @classmethod
    def __get_wordlist_word(cls, soup):
        words = []
        word_lists = soup.find('table', class_='table table-bordered table-striped').find_all('tr')
        # 没有获取到单词，返回None
        if len(word_lists) == 0:
            return None

        for word_list in word_lists:
            word = word_list.find('strong')
            words.append(word.string)

        return words

    @classmethod
    def get_word_annotation(cls, word_main_content):
        word_annotation = []
        soup = BeautifulSoup(word_main_content, 'html.parser')
        annotations = soup.find('div', id='ex-sys-box').find_all('li')
        for annotation in annotations:
            annotation_enex = annotation.find('div', class_='annotation enex')
            if annotation_enex is None or annotation_enex.string is None:
                annotation_enex_string = ''
            else:
                annotation_enex_string = annotation_enex.string.strip()
            annotation_cnex = annotation.find('div', class_='cnex')
            if annotation_cnex is None or annotation_cnex.string is None:
                annotation_cnex_string = ''
            else:
                annotation_cnex_string = annotation_cnex.string.strip()
            word_annotation.append({'en': annotation_enex_string, 'cn': annotation_cnex_string})

        return word_annotation
